package com.core.MQ;

import com.core.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@Profile("mq-rabbit") // 关键：只有当 "mq-rabbit" profile 激活时，这个Bean才会被创建
@RequiredArgsConstructor
public class RabbitMQProducerImpl implements MessageProducer {

    private final RabbitTemplate rabbitTemplate;

    // 约定好交换机名称，也可以从配置读取
    private static final String DEFAULT_EXCHANGE = "reservation.exchange";

    @Override
    public void sendMessage(String topic, Object payload) {
        log.info("使用 RabbitMQ 发送消息. Topic (RoutingKey): {}, Payload: {}", topic, payload);
        try {
            // 在RabbitMQ中，"topic" 参数被用作 routingKey
            log.info("当前 MessageConverter: {}", rabbitTemplate.getMessageConverter().getClass().getName());
            rabbitTemplate.convertAndSend(DEFAULT_EXCHANGE, topic, payload);
        } catch (Exception e) {
            log.error("RabbitMQ 消息时发送失败. Topic: {}, Payload: {}", topic, payload, e);
            // 这里可以根据业务需求决定是否抛出异常或进行其他处理
            throw new BusinessException("RabbitMQ 消息时发送失败");
        }
    }
}